package me.pearjelly;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import me.pearjelly.crawler.DefaultImgCrawler;
import me.pearjelly.dao.CrawlerDao;
import me.pearjelly.dao.hibernate.CrawlerDaoImpl;
import me.pearjelly.model.Crawler;
import me.pearjelly.task.PageTask;
import me.pearjelly.task.impl.ProcessPicTask;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import edu.uci.ics.crawler4j.crawler.CrawlController;

public class CatchController {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int numberOfCrawlers = 10;
		int numberOfTask = 1;

		ApplicationContext context = new ClassPathXmlApplicationContext(
				"classpath:applicationContext.xml");
		ExecutorService executorService = Executors.newCachedThreadPool();
		List<PageTask> pageTasks = new ArrayList<PageTask>(numberOfTask);
		for (int i = 0; i < numberOfTask; i++) {
			PageTask pageTask = new ProcessPicTask();
			context.getAutowireCapableBeanFactory().autowireBean(pageTask);
			pageTasks.add(pageTask);
			executorService.submit(pageTask);
		}

		CrawlerDao crawlerDao = new CrawlerDaoImpl();
		context.getAutowireCapableBeanFactory().autowireBean(crawlerDao);
		List<Crawler> crawlers = crawlerDao.findAll();

		for (Crawler crawler : crawlers) {
			try {
				if (crawler.getStatus() == 0 || crawler.getStatus() == 2) {
					CrawlController controller;
					controller = new CrawlController(crawler.getWorkDir());
					for (String seed : crawler.getSeeds().split("[|]")) {
						controller.addSeed(seed);
					}
					DefaultImgCrawler.configure(crawler);
					controller.start(DefaultImgCrawler.class, numberOfCrawlers);
					crawler.setStatus(1);
					crawlerDao.saveOrUpdate(crawler);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		for (PageTask pageTask : pageTasks) {
			if (null != pageTask) {
				pageTask.destory();
			}
		}
		executorService.shutdown();
	}

}
